package cn.stronglink.oil.user;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.TextHttpResponseHandler;

import java.io.IOException;
import java.net.HttpURLConnection;

import cn.stronglink.oil.MyApplication;
import cn.stronglink.oil.R;
import cn.stronglink.oil.entity.CommonResult;
import cn.stronglink.oil.entity.Result;
import cn.stronglink.oil.exceptions.BusinessErrorException;
import cn.stronglink.oil.exceptions.NetworkCanNotConnectException;
import cn.stronglink.oil.utils.HttpClientUtils;
import cn.stronglink.oil.utils.NetworkUtil;
import cz.msebera.android.httpclient.Header;

/**
 * Created by Tgb on 2017/10/19.
 * 登录逻辑处理
 */

public class LoginModel implements ILoginModel {
   private Gson gson = new Gson();
    @Override
    public void login(final String userName,final String password, final OnLoginListener listener) {
        if (password.isEmpty()){
            listener.loginFail(new BusinessErrorException(MyApplication.getInstance().getString(R.string.input_password)));
            return;
        }
        if (!NetworkUtil.isNetworkAvailable(MyApplication.getInstance())){
            listener.loginFail(new NetworkCanNotConnectException());
            return;
        }
        try {
            HttpClientUtils.login(userName, password, new TextHttpResponseHandler() {
                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                    listener.loginFail(new BusinessErrorException(MyApplication.getInstance().getString(R.string.load_fail)));
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    if (statusCode == HttpURLConnection.HTTP_OK && responseString != null && !responseString.isEmpty()) {
                        Result<User> result  = gson.fromJson(responseString,
                                new TypeToken<Result<User>>() {
                                }.getType());
                        if (result.getHttpCode()==200) {
                            listener.loginSuccess(result.getData());
                        } else {
                            listener.loginFail(new BusinessErrorException(result.getMsg()));
                        }
                    } else {
                        listener.loginFail(new BusinessErrorException(MyApplication.getInstance().getString(R.string.load_fail)));
                    }
                }
            });
        }catch (Exception e){
            listener.loginFail(new BusinessErrorException(MyApplication.getInstance().getString(R.string.load_fail)));
        }
    }
}
